import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import('../views/HomeView.vue')
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/LoginView.vue')
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/RegisterView.vue')
  },
  {
    path: '/products',
    name: 'Products',
    component: () => import('../views/ProductListView.vue')
  },
  {
    path: '/cart',
    name: 'Cart',
    component: () => import('../views/CartView.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/orders',
    name: 'Orders',
    component: () => import('../views/OrderListView.vue'),
    meta: { requiresAuth: true }
  },
  // 管理员路由
  {
    path: '/admin/products',
    name: 'AdminProducts',
    component: () => import('../views/admin/ProductManage.vue'),
    meta: { requiresAuth: true, role: 'ADMIN' }
  },
  // 卖家路由
  {
    path: '/seller/orders',
    name: 'SellerOrders',
    component: () => import('../views/seller/OrderManage.vue'),
    meta: { requiresAuth: true, role: 'SELLER' }
  },
  // 错误
  {
    path: '/:pathMatch(.*)*', // 匹配所有未定义路由
    name: 'NotFound',
    component: () => import('../views/NotFoundView.vue')
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 路由守卫 - 检查认证和角色
router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('token')
  const userRole = localStorage.getItem('role')

  // 需要登录但未登录
  if (to.meta.requiresAuth && !isAuthenticated) {
    next({
      path: '/login',
      query: { redirect: to.fullPath } // 添加重定向参数
    });
    return
  }

  // 需要特定角色但不符合
  if (to.meta.role && userRole !== to.meta.role) {
    alert('您没有访问此页面的权限')
    next('/')
    return
  }

  next()
})

export default router
